#include "stdafx.h"
#include "ScanBookBuilder.h"
#include "Base64.h"

static char alphabet_map[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
static char reverse_map[] =
{
    (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1,
    (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1,
    (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, 62, (char)-1, (char)-1,
    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1,
    (char)-1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, (char)-1, (char)-1, (char)-1, (char)-1, 63,
    (char)-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
    41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, (char)-1, (char)-1, (char)-1, (char)-1, (char)-1
};

int Base64_url_encode(const unsigned char *text, int text_len, unsigned char *encode)
{
    int i, j;
    for (i = 0, j = 0; i+3 <= text_len; i+=3)
    {
        encode[j++] = alphabet_map[text[i]>>2];
        encode[j++] = alphabet_map[((text[i]<<4)&0x30)|(text[i+1]>>4)];
        encode[j++] = alphabet_map[((text[i+1]<<2)&0x3c)|(text[i+2]>>6)];
        encode[j++] = alphabet_map[text[i+2]&0x3f];
    }

    if (i < text_len)
    {
        int tail = text_len - i;
        if (tail == 1)
        {
            encode[j++] = alphabet_map[text[i]>>2];
            encode[j++] = alphabet_map[(text[i]<<4)&0x30];
            //encode[j++] = '=';
            //encode[j++] = '=';
        }
        else
        {
            encode[j++] = alphabet_map[text[i]>>2];
            encode[j++] = alphabet_map[((text[i]<<4)&0x30)|(text[i+1]>>4)];
            encode[j++] = alphabet_map[(text[i+1]<<2)&0x3c];
            //encode[j++] = '=';
        }
    }
	encode[j] = 0;
    return j;
}

int Base64_url_decode(const unsigned char *code, int code_len, unsigned char *plain)
{
    // assert((code_len&0x03) == 0);

    int i, j = 0;
    unsigned char quad[4];
    for (i = 0; i < code_len; i+=4)
    {
        int k;
        for (k = 0; k < 4 && (i+k) < code_len; k++)
        {
            quad[k] = (unsigned char)reverse_map[code[i+k]];
        }
        while(k<4) quad[k++] = 255;

        // assert( quad[0] > 0 && quad[1] > 0 && quad[0] < 64 && quad[1] < 64 );

        plain[j++] = (quad[0]<<2)|(quad[1]>>4);

        if (quad[2] == 255)
        {
            break;
        }
        else if (quad[3] == 255)
        {
            plain[j++] = (quad[1]<<4)|(quad[2]>>2);
            break;
        }
        else
        {
            plain[j++] = (quad[1]<<4)|(quad[2]>>2);
            plain[j++] = (quad[2]<<6)|quad[3];
        }
    }
	plain[j] = 0;
    return j;
}

